package com.originskyseed.platform.course.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.course.i18n.CourseResponseMsg;
import com.originskyseed.platform.course.model.Course;
import com.originskyseed.platform.course.model.CourseStudyRecord;
import com.originskyseed.platform.course.service.ICourseService;
import com.originskyseed.platform.course.service.ICourseStudyRecordService;
import com.originskyseed.platform.course.vo.request.CourseStudyRecordRequestVO;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IPlayerRelateConsumeService;
import com.originskyseed.platform.user.service.IPlayerRelateRechargeService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 课程学习记录表Controller类（OSI_COURSE_STUDY_RECORD）
 *
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/courseStudyRecord")
@BaseLocaleResource(localeFileName = "i18n_course")
public class CourseStudyRecordController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CourseStudyRecordController.class);

	@DubboReference
	private ICourseStudyRecordService courseStudyRecordService;

	@DubboReference
	private ICourseService courseService;

	@DubboReference
	private IPlayerRelateRechargeService playerRelateRechargeService;

	@DubboReference
	private IPlayerRelateConsumeService playerRelateConsumeService;

	@DubboReference
	private IUserInfoService userInfoService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseStudyRecordList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CourseStudyRecord>> courseStudyRecordList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CourseStudyRecord>> result = null;
		try {
			// 请求对象
			CourseStudyRecordRequestVO requestVO = this.getParameterBean(CourseStudyRecordRequestVO.class);

			// 分页查询
			BasePage<CourseStudyRecord> page = new BasePage<CourseStudyRecord>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.courseStudyRecordService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<CourseStudyRecord>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CourseStudyRecord>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseStudyRecordSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<CourseStudyRecord> courseStudyRecordSave(HttpServletRequest request) {
		BaseResponseBody<CourseStudyRecord> result = null;
		try {
			// 请求对象
			CourseStudyRecord courseStudyRecord = this.getParameterBean(CourseStudyRecord.class);

			if (StringUtils.isNotBlank(courseStudyRecord.getId())) {
				this.courseStudyRecordService.updateByPrimaryKey(courseStudyRecord);
			} else {
				this.courseStudyRecordService.insertSelective(courseStudyRecord);
			}
			result = new BaseResponseBody<CourseStudyRecord>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_SUCCESS.getMsg()), courseStudyRecord);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CourseStudyRecord>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseStudyRecordDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> courseStudyRecordDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.courseStudyRecordService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 观看视频修改时间
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateCourseStudyRecord.json", method = RequestMethod.POST)
	public BaseResponseBody<CourseStudyRecord> updateCourseStudyRecord(HttpServletRequest request) {
		BaseResponseBody<CourseStudyRecord> result = null;
		try {
			// 获取当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 请求对象
			CourseStudyRecord courseStudyRecord = this.getParameterBean(CourseStudyRecord.class);
			// 查询是否有记录
			CourseStudyRecord query = new CourseStudyRecord();
			query.setTaskId(courseStudyRecord.getTaskId());
			query.setCreatorId(userInfo.getId());
			query.setCourseId(courseStudyRecord.getCourseId());
			List<CourseStudyRecord> courseStudyRecordList = this.courseStudyRecordService.selectList(query);
			if (courseStudyRecord.getIsComplete() != null && courseStudyRecord.getIsComplete() == 1) {
				if (courseStudyRecordList.size() == 0) {
					courseStudyRecord.setStatus(1);
					courseStudyRecord.setCreatorId(userInfo.getId());
					courseStudyRecord.setCreator(userInfo.getName());
					courseStudyRecord.setUpdateTime(new Date());
					courseStudyRecord.setFinishTime(new Date());
					this.courseStudyRecordService.insertSelective(courseStudyRecord);
				}
			} else {
				if (courseStudyRecordList.size() > 0) {
					CourseStudyRecord courseStudyRecordUpdate = courseStudyRecordList.get(0);
					if (courseStudyRecord.getLearnedDuration().compareTo(courseStudyRecord.getTotalDuration().subtract(new BigDecimal(5))) >= 0) {
						courseStudyRecordUpdate.setStatus(1);
						courseStudyRecordUpdate.setFinishTime(new Date());
					} else {
						courseStudyRecordUpdate.setStatus(0);
					}
					this.courseStudyRecordService.updateByPrimaryKeySelective(courseStudyRecordUpdate);
				} else {
					if (courseStudyRecord.getLearnedDuration().compareTo(courseStudyRecord.getTotalDuration().subtract(new BigDecimal(5))) >= 0) {
						courseStudyRecord.setStatus(1);
						courseStudyRecord.setFinishTime(new Date());
					} else {
						courseStudyRecord.setStatus(0);
					}
					courseStudyRecord.setCreatorId(userInfo.getId());
					courseStudyRecord.setCreator(userInfo.getName());
					courseStudyRecord.setUpdateTime(new Date());
					this.courseStudyRecordService.insertSelective(courseStudyRecord);
				}
			}
			// 播放量加1
			Course course = this.courseService.selectByPrimaryKey(courseStudyRecord.getCourseId());
			if (course != null) {
				if (course.getPlayVolume() != null) {
					course.setPlayVolume(course.getPlayVolume() + 1);
				} else {
					course.setPlayVolume(1);
				}
				this.courseService.updateByPrimaryKeySelective(course);
			}
			result = new BaseResponseBody<CourseStudyRecord>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_SUCCESS.getMsg()), courseStudyRecord);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CourseStudyRecord>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 判断该用户是否有学习课程
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userCourseIsStudyRecord.json", method = RequestMethod.POST)
	@RequiredParams(names = { "courseId", "taskId" })
	public BaseResponseBody userCourseIsStudyRecord(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 获取当前用户信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			String courseId = this.getParameterString("courseId", null);
			String taskId = this.getParameterString("taskId", null);
			List<String> courses = Arrays.asList(courseId.split(","));
			List<String> courseName = new ArrayList<>();
			if (courses != null && courses.size() > 0) {
				for (String course : courses) {
					// 查询是否有记录
					CourseStudyRecord courseStudyRecord = this.courseStudyRecordService.selectIsStudy(courseId, userInfo.getId(), 2, taskId);
					if (courseStudyRecord != null) {
						Course name = this.courseService.selectByPrimaryKey(courseId);
						courseName.add(name.getName());
					}
				}
			}
			// 有没学完的课程
			StringBuffer courseNames = new StringBuffer();
			if (courseName.size() > 0) {
				for (String s : courseName) {
					courseNames.append(s + ",");
				}
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SOURCE_NOT_STUDY_ERROR.getMsg()) + "你的课程： " + courseNames.substring(0, courseNames.length() - 1) + "还没完成学习，请完成课程学习再参加考试！", null);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询学习情况
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectStudySituation.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody selectLearningSituation(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			CourseStudyRecordRequestVO requestVO = this.getParameterBean(CourseStudyRecordRequestVO.class);

			// 分页查询
			BasePage<CourseStudyRecord> page = new BasePage<CourseStudyRecord>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.courseStudyRecordService.selectStudySituationByPage(requestVO.toMap(), page);
			for (CourseStudyRecord courseStudyRecord : page.getResults()) {
				UserInfo userInfo = this.userInfoService.selectByPrimaryKey(courseStudyRecord.getCreatorId());
				if (userInfo != null && courseStudyRecord.getStatus() != null && courseStudyRecord.getStatus() == 2) {
					BigDecimal lastAmount = BigDecimal.ZERO;
					BigDecimal nextAmount = BigDecimal.ZERO;

					List<String> lastTimeList = getLastTimeInterval(courseStudyRecord.getUpdateTime());
					List<String> endTimeList = getNextTimeInterval(courseStudyRecord.getUpdateTime());
					Map<String, Object> lastMap = new HashMap<>();
					Map<String, Object> nextMap = new HashMap<>();
					lastMap.put("startTime", lastTimeList.get(0));
					lastMap.put("endTime", lastTimeList.get(1));

					nextMap.put("startTime", endTimeList.get(0));
					nextMap.put("endTime", endTimeList.get(1));
					// 内容类
					if (userInfo.getSourceSys() == 1) {
						lastMap.put("anchorId", userInfo.getOtherAccount());
						nextMap.put("anchorId", userInfo.getOtherAccount());
						lastAmount = this.playerRelateConsumeService.selectTotalAmountByMap(lastMap);
						nextAmount = this.playerRelateConsumeService.selectTotalAmountByMap(nextMap);
						// 推广类
					} else if (userInfo.getSourceSys() == 2) {
						lastMap.put("channelSubId", userInfo.getOtherAccount());
						nextMap.put("channelSubId", userInfo.getOtherAccount());
						lastAmount = this.playerRelateRechargeService.selectTotalAmountByMap(lastMap);
						nextAmount = this.playerRelateRechargeService.selectTotalAmountByMap(nextMap);
					}
					courseStudyRecord.setLastWeekRevenue(lastAmount);
					courseStudyRecord.setWeekRevenue(nextAmount);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 获取指定时间上周开始时间和结束时间
	 * 
	 * @param date
	 * @return
	 */
	public List<String> getLastTimeInterval(Date date) {
		List<String> list = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date);
		calendar2.setTime(date);
		int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
		if (dayOfWeek <= 0) {
			dayOfWeek = 7;
		}
		int offset1 = 1 - dayOfWeek;
		int offset2 = 7 - dayOfWeek;
		calendar1.add(Calendar.DATE, offset1 - 7);
		calendar2.add(Calendar.DATE, offset2 - 7);
		// last Monday
		String lastBeginDate = sdf.format(calendar1.getTime());
		// last Sunday
		String lastEndDate = sdf.format(calendar2.getTime());
		list.add(lastBeginDate);
		list.add(lastEndDate);
		return list;
	}

	/**
	 * 获取指定时间的下一周开始时间和结束时间
	 * 
	 * @param date
	 * @return
	 */
	public List<String> getNextTimeInterval(Date date) {
		List<String> list = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date);
		calendar2.setTime(date);
		int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
		if (dayOfWeek <= 0) {
			dayOfWeek = 7;
		}
		int offset1 = 1 - dayOfWeek;
		int offset2 = 7 - dayOfWeek;
		calendar1.add(Calendar.DATE, offset1 + 7);
		calendar2.add(Calendar.DATE, offset2 + 7);
		// last Monday
		String lastBeginDate = sdf.format(calendar1.getTime());
		// last Sunday
		String lastEndDate = sdf.format(calendar2.getTime());
		list.add(lastBeginDate);
		list.add(lastEndDate);
		return list;
	}
}
